<template>
  <div class="form-item">
    <div class="page-header">
      <!-- <h2 class="page-title">表单项管理</h2> -->
      <el-button type="primary" class="add-button" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>

    <div class="content-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 600,
        }"
      >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="iconUrl" label="图标链接">
          <template #default="scope">
            <div class="image-preview-list">
              <el-image
                v-if="scope.row.iconImages && scope.row.iconImages.length > 0"
                :src="scope.row.iconImages[0]"
                style="width: 50px; height: 50px"
                :preview-src-list="scope.row.iconImages"
                preview-teleported
                fit="cover"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="qrCodeUrl" label="二维码链接">
          <template #default="scope">
            <div class="image-preview-list">
              <el-image
                v-if="scope.row.qrCodeImages && scope.row.qrCodeImages.length > 0"
                :src="scope.row.qrCodeImages[0]"
                style="width: 50px; height: 50px"
                :preview-src-list="scope.row.qrCodeImages"
                preview-teleported
                fit="cover"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" />
        <el-table-column prop="isVisible" label="是否显示">
          <template #default="scope">
            <el-tag :type="scope.row.isVisible ? 'success' : 'info'">
              {{ scope.row.isVisible ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增项目' : '编辑项目'"
      width="50%"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="图标" prop="iconUrl">
          <custom-upload
            v-model="form.iconUrl"
            display-type="picture-wall"
            list-type="picture-card"
            :limit="1"
            :file-types="[1]"
          />
        </el-form-item>
        <el-form-item label="二维码" prop="qrCodeUrl">
          <custom-upload
            v-model="form.qrCodeUrl"
            display-type="picture-wall"
            list-type="picture-card"
            :limit="1"
            :file-types="[1]"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isVisible">
          <el-switch v-model="form.isVisible" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getItemsList, deleteItem, createItem } from '@/api/zhaokao/systemweb';
import { ElMessage, ElMessageBox } from 'element-plus';
import customUpload from '@/components/upload/index.vue';
import { Plus } from '@element-plus/icons-vue';

const tableData = ref([]);
const dialogVisible = ref(false);
const dialogType = ref('add');
const formRef = ref(null);
const form = ref({
  name: '',
  description: '',
  iconUrl: '',
  qrCodeUrl: '',
  sortOrder: 0,
  isVisible: true,
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度应在2到50个字符之间', trigger: 'blur' },
  ],
  iconUrl: [{ required: true, message: '请上传图标', trigger: 'change' }],
  qrCodeUrl: [{ required: true, message: '请上传二维码', trigger: 'change' }],
  sortOrder: [{ required: true, message: '请设置排序值', trigger: 'change' }],
};

// 获取列表数据
const fetchData = async () => {
  try {
    const res = await getItemsList({
      pageNum: 1,
      pageSize: -1,
    });
    if (res.success && res.code === 200) {
      res.data.records.forEach(item => {
        try {
          // 处理图标图片
          const iconData = JSON.parse(item.iconUrl);
          if (Array.isArray(iconData) && iconData.length > 0) {
            item.iconImages = iconData.map(img => img.downloadUri || img.url).filter(Boolean);
          } else {
            item.iconImages = [];
          }

          // 处理二维码图片
          const qrCodeData = JSON.parse(item.qrCodeUrl);
          if (Array.isArray(qrCodeData) && qrCodeData.length > 0) {
            item.qrCodeImages = qrCodeData.map(img => img.downloadUri || img.url).filter(Boolean);
          } else {
            item.qrCodeImages = [];
          }
        } catch (error) {
          console.error('解析图片数据失败:', error);
          item.iconImages = [];
          item.qrCodeImages = [];
        }
      });
      tableData.value = res.data.records;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('获取列表数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 新增
const handleAdd = () => {
  dialogType.value = 'add';
  form.value = {
    name: '',
    description: '',
    iconUrl: '',
    qrCodeUrl: '',
    sortOrder: 0,
    isVisible: true,
  };
  dialogVisible.value = true;
  // 在下一个渲染循环清除表单验证
  if (formRef.value) {
    setTimeout(() => {
      formRef.value.clearValidate();
    });
  }
};

// 编辑
const handleEdit = row => {
  dialogType.value = 'edit';
  form.value = { ...row };
  try {
    // 处理图标图片数据
    const iconImages = JSON.parse(row.iconUrl);
    form.value.iconUrl = iconImages.map(img => ({
      ...img,
      uid: img.uid || Date.now() + Math.random().toString(36).substr(2, 8),
      status: 'success',
      url: img.url || img.downloadUri,
    }));

    // 处理二维码图片数据
    const qrCodeImages = JSON.parse(row.qrCodeUrl);
    form.value.qrCodeUrl = qrCodeImages.map(img => ({
      ...img,
      uid: img.uid || Date.now() + Math.random().toString(36).substr(2, 8),
      status: 'success',
      url: img.url || img.downloadUri,
    }));
  } catch (error) {
    console.error('解析图片数据失败:', error);
    form.value.iconUrl = [];
    form.value.qrCodeUrl = [];
  }

  dialogVisible.value = true;
  // 在下一个渲染循环清除表单验证
  if (formRef.value) {
    setTimeout(() => {
      formRef.value.clearValidate();
    });
  }
};

// 删除
const handleDelete = row => {
  ElMessageBox.confirm('确定要删除该项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteItem(row.id);
      ElMessage.success('删除成功');
      fetchData();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  formRef.value.validate(async valid => {
    if (valid) {
      try {
        const submitForm = { ...form.value };

        // 处理图标图片数据
        if (Array.isArray(submitForm.iconUrl)) {
          const formattedIconImages = submitForm.iconUrl.map(img => ({
            name: img.name,
            downloadUri: img.downloadUri || img.url,
            filename: img.filename || img.name,
            uploadPath: img.uploadPath || '',
            url: img.url || img.downloadUri,
          }));
          submitForm.iconUrl = JSON.stringify(formattedIconImages);
        } else if (!submitForm.iconUrl) {
          submitForm.iconUrl = '[]';
        }

        // 处理二维码图片数据
        if (Array.isArray(submitForm.qrCodeUrl)) {
          const formattedQrCodeImages = submitForm.qrCodeUrl.map(img => ({
            name: img.name,
            downloadUri: img.downloadUri || img.url,
            filename: img.filename || img.name,
            uploadPath: img.uploadPath || '',
            url: img.url || img.downloadUri,
          }));
          submitForm.qrCodeUrl = JSON.stringify(formattedQrCodeImages);
        } else if (!submitForm.qrCodeUrl) {
          submitForm.qrCodeUrl = '[]';
        }

        await createItem(submitForm);
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功');
        dialogVisible.value = false;
        fetchData();
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败');
      }
    } else {
      ElMessage.warning('请正确填写表单信息');
      return false;
    }
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.form-item {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #1f2f3d;
  margin: 0;
  font-weight: 600;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 10px 20px;
  font-weight: 500;
}

.content-card {
  background: #ffffff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.image-preview-list {
  position: relative;
  display: inline-block;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.image-preview-list .el-image {
  transition: transform 0.3s ease;
}

.image-preview-list:hover .el-image {
  transform: scale(1.05);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-button.el-button--primary.is-link) {
  font-weight: 500;
}

:deep(.el-button.el-button--danger.is-link) {
  font-weight: 500;
}

:deep(.custom-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.custom-dialog .el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 24px;
}

:deep(.custom-dialog .el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #dcdfe6;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 4px 8px;
}

:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
